package com.example.week04_work2;

import java.util.concurrent.CountDownLatch;

/**
 * @author nhsoft.ll
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws Exception{
        long start = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(1);
        CountDownLatchDemoSumTask sumTask = new CountDownLatchDemoSumTask(latch);
        sumTask.start();
        latch.await();
        System.out.println("异步计算结果为：" + sumTask.getResult());
        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");
    }
}

class CountDownLatchDemoSumTask extends Thread {

    private int result;

    private CountDownLatch latch;

    public CountDownLatchDemoSumTask(CountDownLatch latch) {
        this.latch = latch;
    }

    public int getResult() {
        return result;
    }

    @Override
    public void run() {
        result = sum();
        System.out.println("线程运行结果:" + result);
        this.latch.countDown();
    }

    private int sum() {
        return fibo(36);
    }

    private int fibo(int a) {
        if (a < 2)
            return 1;
        return fibo(a - 1) + fibo(a - 2);
    }
}



